require.config({
    paths: {
        'html2canvas': "../addons/fastflow/plugins/html2canvas/html2canvas.min",
        'compression': "../addons/fastflow/plugins/compression/compression",
        'qrcode': "../addons/fastflow/plugins/node-qrcode-master/qrcode.min",
    },
    shim:{
        'qrcode': {
            deps: ['jquery'],
            exports: 'QRCode'
        },
    }
});

define(['jquery', 'bootstrap', 'backend', 'form', 'html2canvas', 'compression', 'qrcode'], function ($, undefined, Backend, Form, Html2canvas, Compression, QRCode) {

    var Controller = {
        currentBillId: null,
        base64: null,
        preview: function () {
            var index = layer.load();
            if(Config.hasSignature === true){
                containerWidth = $('#ebill').css('width').replace('px','');
                contentWidth = $('#ebill-content').css('width').replace('px','');
                $('#ebill').animate({scrollLeft:(contentWidth - containerWidth + 12) / 2},0);
                layer.close(index);
                return;
            }
            if (Config.qrcode == "true"){
                var pos = {
                    "topleft":"top:30px;left:30px;",
                    "topright":"top:30px;right:30px;",
                    "bottomleft":"bottom:30px;left:30px;",
                    "bottomright":"bottom:30px;right:30px;"
                };
                var img = '<image class="qrcode" style="' + pos[Config.qrcodepos] + 'height: ' + Config.qrcodesieze + 'px; width: ' + Config.qrcodesieze + 'px;">';
                $('section','#ebill-html').append(img);
                QRCode.toDataURL(Config.detail_url, { errorCorrectionLevel: 'M'}, function (err, url) {
                    $('.qrcode').attr('src', url);
                });
            }

            Controller.api.screenShot('ebill-html', function (canvas) {
                if (canvas !== null) {
                    var canvasWidth = canvas.width;
                    var canvasHeight = canvas.height;
                    var div = document.createElement('div');
                    $(div)
                        .css('width', canvasWidth)
                        .css('height', canvasHeight)
                        .css('backgroundImage', "url(" + canvas.toDataURL() + ")")
                        .css('margin', '0px auto 0px auto')
                        .attr('id', 'ebill-content')
                        .attr('data-fswidth', $('section:first', '#ebill-html').css('width'))
                        .attr('data-fsheight', $('section:first', '#ebill-html').css('height'))
                        .attr('data-title',Config.bill_name !== undefined ? Config.bill_name + '(' + Config.bill_id + ')电子表单' : '');
                    $('#ebill').html(div);

                    containerWidth = $('#ebill').css('width').replace('px','');
                    contentWidth = $(div).css('width').replace('px','');
                    $('#ebill').animate({scrollLeft:(contentWidth - containerWidth + 12) / 2},0);
                }
                var parentSubmitBtn = parent.$('#ebill-form #submit', parent.document);
                if (parentSubmitBtn.length !== 0) {
                    canvas === null ? parentSubmitBtn.addClass('disabled') : parentSubmitBtn.removeClass('disabled');
                }
                layer.close(index);
            });
        },
        index: function () {
            Controller.api.refreshEbillList();
            require.config({
                paths: {
                    'classie': "../addons/fastflow/plugins/select/js/classie",
                    'SelectFx': "../addons/fastflow/plugins/select/js/selectFx",
                },
                shim: {
                    'classie': {
                        exports: 'classie'
                    },
                    'SelectFx': {
                        exports: 'SelectFx'
                    },
                },
            });
            require(['classie', 'SelectFx', 'template'], function (classie, SelectFx, Template) {
                var select = document.getElementById('bill-select');
                window.classie = classie;
                new SelectFx(select, {
                    onChange: function (val) {
                        Controller.currentBillId = val;
                        Controller.api.refreshEbillList();
                    }
                });
            });
            Controller.api.bindListToolBarEvent();
        },
        add: function () {
            Controller.api.bindAddEditEvent();
        },
        edit: function () {
            Controller.api.bindAddEditEvent();
        },
        api: {
            bindAddEditEvent: function () {
                //上传成功回调
                $('#faupload-file').data('upload-success', function () {
                    var file = $('input[name="row[file]"]').val();
                    $('#ebill-iframe').attr('src', 'preview?action=preview&file=' + file);
                });
                //监听文件变化
                $('#file-preview').on('fa.preview.change', function () {
                    $('#ebill-iframe').attr('src', '');
                    $('#submit').addClass('disabled');
                });
                $('#submit').on('click', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    var ebillContent = $('#ebill-iframe').contents().find('#ebill-content');
                    if (ebillContent.length === 0) {
                        Toastr.error('文件格式错误，请重新选择Word2007及更高版本文件');
                        $('#submit').addClass('disabled');
                        return false;
                    }
                    var ebillImage = ebillContent.css('backgroundImage').replace('url("', '').replace('")', '');
                    var thumWidth = ebillContent.data('fswidth').replace('px', '');
                    var thumHeight = ebillContent.data('fsheight').replace('px', '');
                    Compression.Clipping(ebillImage, thumWidth, thumHeight, 1, function (result) {
                        //处理base64字符串，将特殊符号%、&、+等进行转义
                        result = result
                            .replace(/%/g, "%25")
                            .replace(/&/g, "%26")
                            .replace(/\+/g, "%2B");
                        $.ajax({
                            type: "post",
                            url: location.href,
                            data: $('#ebill-form').serialize()
                                + '&file=' + $('input[name="row[file]"]').val()
                                + '&thumb_width=' + ebillContent.css('width')
                                + '&thumb_height=' + ebillContent.css('height')
                                + '&thumbnail=' + result,
                            success: function (data) {
                                if (data['code'] === 1) {
                                    parent.Toastr.success(data['msg']);
                                    let index = parent.Layer.getFrameIndex(window.name);
                                    parent.Layer.close(index);
                                    parent.$('#refresh-ebill', parent.document).trigger('click');
                                } else if (data['code'] === 0) {
                                    Toastr.error(data['msg']);
                                }
                            },
                        });
                    });
                });
                Form.api.bindevent($("form[role=form]"));
            },
            bindListToolBarEvent: function () {
                $('#add-ebill').click(function (e) {
                    $(this).data('area', ['95%', '95%']);
                    Fast.api.open('fastflow/flow/ebill/add?bill_id=' + Controller.currentBillId, '添加电子表单', $(this).data() || {});
                });
                $('#refresh-ebill').click(function (e) {
                    Controller.api.refreshEbillList();
                });
            },
            bindEbillTrashEvent: function () {
                $('.ebill-trash').click(function (e) {
                    ebillId = $(this).data('id');
                    var that = this;
                    var top = $(that).offset().top - $(window).scrollTop();
                    var left = $(that).offset().left - $(window).scrollLeft() - 160;
                    if (top + 154 > $(window).height()) {
                        top = top - 154;
                    }
                    if ($(window).width() < 480) {
                        top = left = undefined;
                    }
                    Layer.confirm(
                        __('确定删除吗?'),
                        {
                            icon: 3,
                            title: __('Warning'),
                            offset: [top, left],
                            shadeClose: true,
                            btn: [__('OK'), __('Cancel')]
                        },
                        function (index) {
                            $.ajax({
                                type: "post",
                                url: "fastflow/flow/ebill/del",
                                data: {
                                    ids: ebillId
                                },
                                success: function (data) {
                                    if (data['code'] == 1) {
                                        Toastr.success('删除成功');
                                        Controller.api.refreshEbillList();
                                    } else if (data['code'] == 0) {
                                        Toastr.error(data['msg']);
                                    }
                                    layer.close(index);
                                },
                                error: function (e) {
                                    layer.close(index);
                                }
                            });
                            Layer.close(index);
                        }
                    );
                });
            },
            bindEbillThumbnailEvent: function () {
                $('.imgProd', '#contenedorCards').click(function () {
                    let ebillId = $(this).data('id');
                    let title = $(this).data('title');
                    $(this).data('area', ['75%', '90%']);
                    Fast.api.open('fastflow/flow/ebill/preview?id=' + ebillId + '&action=preview', title, $(this).data() || {});
                });
                $('.preview-btn', '#contenedorCards').click(function (e) {
                    var ebillThumbnail = $(this).closest('.wrapper').find('.imgProd')[0];
                    ebillThumbnail.click();
                });
            },
            bindEbillEditEvent: function () {
                $('.ebill-edit').click(function (e) {
                    $(this).data('area', ['95%', '95%']);
                    Fast.api.open('fastflow/flow/ebill/edit?ids=' + $(this).data('id'), '编辑电子表单', $(this).data() || {});
                });
            },
            refreshEbillList: function () {
                var index = layer.load();
                Controller.currentBillId = Controller.currentBillId === null ? $('option:first', '#bill-select').attr('value') : Controller.currentBillId;
                $.ajax({
                    type: "get",
                    url: location.href,
                    data: {
                        bill_id: Controller.currentBillId
                    },
                    success: function (data) {
                        if (data['code'] == 1) {

                            $('.ebill-trash').unbind('click');
                            $('.imgProd', '.ebill-list').unbind('click');
                            $('.preview-btn').unbind('click');
                            $('.ebill-edit').unbind('click');

                            var ebills = data['ebills'];
                            var html = Template('itemTpl', {list: ebills});
                            document.getElementById('contenedorCards').innerHTML = html;
                            ebills.length !== 0 ? $('.empty-hint').hide() : $('.empty-hint').show();

                            Controller.api.bindEbillTrashEvent();
                            Controller.api.bindEbillThumbnailEvent();
                            Controller.api.bindEbillEditEvent();

                        } else if (data['code'] == 0) {
                            Toastr.error(data['msg']);
                        }
                        layer.close(index);
                    },
                    error: function (e) {
                        layer.close(index);
                    }
                });
            },
            screenShot: function (elementId, callback) {
                var element = document.getElementById(elementId);
                if (element === null) {
                    callback(null);
                    return;
                }
                Html2canvas(element,
                    {
                        useCORS: true,
                        scale: 1,
                        height: element.scrollHeight,
                        windowHeight: element.scrollHeight,
                    }).then(canvas => {
                    callback(canvas);
                });
            }
        }
    };
    return Controller;
});